<template>
  <div class="update-name-container">
    <!--导航栏-->
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <!--/导航栏-->
    <div class="field-wrap">
      <van-field
        type="textarea"
        placeholder="请输入昵称"
        show-word-limit
        maxlength="16"
        autosize
        v-model="localName"
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '../../api/profile'

export default {
  name: 'updateName',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      localName: this.value
    }
  },
  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '更新中……',
        forbidClick: true
      })
      try {
        await updateUserProfile({
          name: this.localName
        })
        // 更新父组件 v-model 绑定的数据
        this.$emit('input', this.localName)
        // 关闭弹出层
        this.$emit('close')
        this.$toast.success('更新成功！')
      } catch (e) {
        if (e && e.response && e.response.status === 409) {
          this.$toast.fail('昵称已存在，更新失败！')
        } else {
          this.$toast.fail('未知错误，更新失败！')
        }
      }
    }
  }
}
</script>

<style scoped>
.van-nav-bar {
  background-color: #FFFFFF;
}
/deep/ .van-nav-bar__title {
  color: #323233;
}
.field-wrap {
  padding: 10px;
}
</style>
